<template>
  <PageModal
    prevent-back
    show-back
    :show="show"
    :page-style="pageStyle"
    :footer-size="footerSize"
    :footer-style="footerStyle"
    :title="$t('UpdateFavorite.Navigate.Title')"
    @back="closeModal"
    @close="closeModal"
  >
    <AdjustParameterView :control="control" :program-name="programName">
      <template #title-icon>
        <image class="rename-icon" src="@/pages/appliance/static/ic_rename.png" @click="updateFavoriteName"></image>
      </template>
      <template #desc>
        <view class="program-desc">{{ desc }}</view>
      </template>
    </AdjustParameterView>

    <template #footer>
      <ActionGroup>
        <ActionButton
          v-if="from === 'addFavorite'"
          :text="$t('UpdateFavorite.Bottom.PrefixStep.Button')"
          @click="closeModal"
        />
        <ActionButton :text="$t('UpdateFavorite.Bottom.Save.Button')" @click="save"> </ActionButton>
      </ActionGroup>
    </template>

    <RenameModal
      name-focus
      v-model:show="renameModalVisible"
      :title="$t('UpdateFavorite.Dialog.Title')"
      :ok-text="$t('UpdateFavorite.Dialog.Ok.Text')"
      :cancel-text="$t('UpdateFavorite.Dialog.Cancle.Text')"
      :nick-name="programName"
      @confirm="confirmRename"
    ></RenameModal>
  </PageModal>
</template>

<script setup lang="ts">
import PageModal from '@/common/pageModal.vue'
import AdjustParameterView from '../view/adjustParameterView.vue'
import ActionGroup from '@/common/actionButton/actionGroup.vue'
import ActionButton from '@/common/actionButton/actionButton.vue'
import RenameModal from '@/common/renameModal.vue'

import type { BaseController } from '@/controller/BaseAppliance/definition'

import { footerStyle, footerSize } from '@/layout/appliance/style'
import type { CSSProperties } from 'vue'
import { actionDebounce } from '@/utils/mpHelper'
import { useI18n } from 'vue-i18n'
import {
  loadKeyIndex,
  setFavorite,
  setFavoriteName,
  setFavoriteOptions,
} from '@/controller/common/Program/FavoriteHelper'
import type { ApplianceDetailOption } from '@/api/appliance'
import { BSH_COMMON_OPRION_BASEPROGRAM, BSH_COMMON_OPTION_PROGRAMNAME } from '@/constants/Command'
import { safeTrack, applianceControlTrack } from '@/dataReport/dataReportUtil'
import { trackEvent, TrackType } from '@/dataReport/tracks'

const i18n = useI18n()

const pageStyle: CSSProperties = {
  backgroundColor: '#ffffff',
}
const ProgramPrefix = 'BSH.Common.Program.Favorite.'

const props = defineProps<{
  show: boolean
  control: BaseController.Control
  from?: string
  isUpdateFavoriteName?: boolean
}>()
const emit = defineEmits<{
  (e: 'update:show', show: boolean): void
  (e: 'close'): void
  (e: 'add-favorite-success'): void
}>()

function closeModal() {
  emit('update:show', false)
  emit('close')
}

const activeProgram = computed(() => props.control.store.currentProgram)
const activeProgramKey = computed(() => props.control.store.currentProgramKey)
const activeProgramName = computed(() => props.control.store.currentProgramName)
const settings = computed(() => props.control.store._datasource.settings)
const desc = computed(
  () => props.control.store.availableParameter?.mediumDescription || activeProgram.value?.mediumDescription
)

const programName = ref('')
watchEffect(() => {
  if (!activeProgramName.value) return
  programName.value = activeProgramName.value
})
const renameModalVisible = ref(false)
function updateFavoriteName() {
  renameModalVisible.value = true
}

/**
 * 确认重命名
 * @param name
 */
function confirmRename(name: string) {
  programName.value = name
  renameModalVisible.value = false
}

/**
 * 点击保存
 */
const save = actionDebounce({
  loadingText: i18n.t('APP.Common.Saving.Text'),
  call: async () => {
    let keyIndex = ''
    let key = activeProgramKey.value
    let name = activeProgramName.value

    if (activeProgramKey.value.indexOf('BSH.Common.Program.Favorite') !== -1) {
      let options = props.control.store.detail?.option
      if (!options || options?.length === 0) return
      options.forEach((item) => {
        if (item.key === BSH_COMMON_OPRION_BASEPROGRAM) {
          name = item.displayvalue as string
          key = item.value as string
        }
      })
    }
    await props.control.remote.loadApplianceDetail()

    let newOptions = [
      {
        key,
        name,
        options: clearOptions(props.control.store.detail?.option as ApplianceDetailOption[]),
      },
    ]

    let res: any = null
    // 更新
    try {
      if (props.from === 'updateFavorite') {
        keyIndex = activeProgramKey.value.replace(ProgramPrefix, '')
        await setFavoriteOptions(props.control.store._datasource.haId, keyIndex, newOptions)
        res = await setFavoriteName(props.control.store._datasource.haId, keyIndex, programName.value)
      } else {
        //新增
        keyIndex = loadKeyIndex('latest', activeProgramKey.value, settings.value)
        res = await setFavorite(props.control.store._datasource.haId, keyIndex, programName.value, newOptions)
      }
    } catch (error) {
      res = error
    } finally {
      if (props.from === 'updateFavorite') {
        safeTrack(() => {
          const trackData: { favorite_value_obj_key: string; favorite_value_obj_value: string | number | boolean }[] =
            []
          newOptions[0].options.map((items, index) => {
            trackData.push({ favorite_value_obj_key: items.key, favorite_value_obj_value: items.value })
          })
          trackEvent(
            'modify_favorite_program',
            {
              program_key: key,
              program_name: name,
              favorite_value_obj: JSON.stringify(trackData),
              successOrNot: res.code == 0,
              error_code: res.code,
              response_msg: res.msg,
            },
            TrackType.ApplianceDetail,
            'Appliance.CoffeeeMaker.AddFavorite.SaveAdjustOption'
          )
        })
      } else {
        //新增
        safeTrack(() => {
          const trackData: { favorite_value_obj_key: string; favorite_value_obj_value: string | number | boolean }[] =
            []
          newOptions[0].options.map((items, index) => {
            trackData.push({ favorite_value_obj_key: items.key, favorite_value_obj_value: items.value })
          })
          trackEvent(
            'favorite_program',
            {
              program_key: newOptions[0].key,
              program_name: newOptions[0].name,
              favorite_value_obj: JSON.stringify(trackData),
              successOrNot: res.code == 0,
              error_code: res.code,
              response_msg: res.msg,
            },
            TrackType.ApplianceDetail,
            'Appliance.CoffeeeMaker.AddFavorite.Favorite'
          )
        })
      }
      uni.showToast({
        title: i18n.t('APP.Common.SaveSucess.Text'),
        icon: 'success',
      })
      await new Promise<void>((resolve) => {
        setTimeout(() => {
          resolve()
          nextTick(() => {
            if (props.from === 'addFavorite') {
              emit('add-favorite-success')
            }
            closeModal()
          })
        }, 2000)
      })
    }
  },
})

/**
 * 清除options中多余数据
 * @param list
 */
function clearOptions(list: ApplianceDetailOption[]) {
  return list.filter((item) => ![BSH_COMMON_OPTION_PROGRAMNAME, BSH_COMMON_OPRION_BASEPROGRAM].includes(item.key))
}
</script>

<style scoped lang="less">
.rename-icon {
  width: 64rpx;
  height: 64rpx;
  margin-left: 10rpx;
  margin-bottom: -16rpx;
  opacity: 0.4;
}
</style>
